package net.lsr.demo.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.lsr.demo.dao.BaseDao;
import net.lsr.demo.domain.Qrcode;
import net.lsr.demo.domain.mapper.QrcodeMapper;
import net.lsr.demo.helper.ContextHelper;
import net.lsr.demo.helper.DateHelper;
import net.lsr.demo.helper.IdGenerator;
import net.lsr.demo.helper.PropertiesHelper;
import net.lsr.demo.helper.qrcode.QrcodeHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

/**
 * desc: 二维码服务实现
 * @author lsr
 * @version 2014年6月4日
 */
@Service
public class QrcodeServiceImpl implements QrcodeService {
	private static final Logger logger = LoggerFactory.getLogger(QrcodeServiceImpl.class);
	@Autowired
	private BaseDao<Qrcode> baseDao;
	@Autowired
	private QrcodeHelper qrcodeHelper;
	@Autowired
	private IdGenerator idGenerator;
	@Autowired
	private ContextHelper contextHelper;
	@Autowired
	private PropertiesHelper propHelper;
	
	@Transactional
	public void addQrcode(Qrcode qrcode) {
		String sql = "insert into t_qrcode(id, day, filePath, generateDate) values (?, ?, ?, ?)";
		Object[] params = new Object[]{
				qrcode.getId(),
				qrcode.getDay(),
				qrcode.getFilePath(),
				qrcode.getGenerateDate()
		};
		baseDao.update(sql, params);
	}

	@Transactional
	public void generateQrcode() {
		// 生成二维码文件
		String defaultFileSuffix = ".jpg";
		String id = idGenerator.generateID();
		String uuid = idGenerator.generateUUID();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("qrKey", uuid);
		String content = JSON.toJSONString(map);
		String contextPath = contextHelper.getContextPath();
		// 路径前缀
		String qrcodeDir = propHelper.getServerQrcodeDir();
		String filePath = qrcodeDir + id + defaultFileSuffix;
		String targetFile = contextPath + filePath;
		logger.info("generateQrcode file path:{}", targetFile);
		qrcodeHelper.generate(content, targetFile);
		
		// 保存二维码
		Qrcode q = new Qrcode();
		q.setId(uuid);
		q.setDay(DateHelper.getNow("yyyy-MM-dd"));
		q.setFilePath(filePath);
		q.setGenerateDate(DateHelper.getNow());
		addQrcode(q);
	}

	@Transactional(readOnly = true)
	public Qrcode queryQrcodeById(String id) {
		String sql = "select * from t_qrcode where id = ?";
		return baseDao.queryByPrimaryKey(sql, new Object[]{id}, new QrcodeMapper());
	}

	@Transactional(readOnly = true)
	public Qrcode showDailyQrcode() {
		String sql = "select * from t_qrcode where day = ? order by generateDate desc";
		List<Qrcode> list =  baseDao.query(sql, new Object[]{DateHelper.getNow("yyyy-MM-dd")}, new QrcodeMapper());
		if(list != null && !list.isEmpty())
			return list.get(0);
		else
			return null;
	}

}
